/**
 * Db2Json allows users to convert their databases into JSON format.
 * 
 * 
 */

package org.thotheolh.db2json;

import java.io.File;
import java.util.ArrayList;

import org.thotheolh.db2json.db.DbCodec;
import org.thotheolh.db2json.db.struct.Table;

public class Db2Json {

	private ArrayList<Table> tableList = new ArrayList<Table>();
	private Table tmp;

	public Db2Json() {

	}

	// Encodes a database (via JDBC) to JSON file once deemed ready after all
	// data have been added. JDBC access would be added later on.
	public void encodeDb(File output) {
		new DbCodec().toJson(tableList, output);
	}

	// Adds data to a new table which would set simply set the isNewTuple to
	// false as a new Table always have a new tuple.
	public void addDataToNewTable(String table, String rowname, Object data) {
		addDataForEncoding(table, rowname, data, false);
	}

	// Adds data to Table before calling encodeDb() to begin encoding.
	public void addDataForEncoding(String table, String rowname, Object data,
			boolean isNewTuple) {
		if (isTableExists(table)) {
			for (int i = 0; i < tableList.size(); i++) {
				tmp = tableList.get(i);
				if (tmp.getTableName().equals(table)) {
					if (isNewTuple) {
						tableList.get(i).nextTuple();
					}
					if (rowname != null || !rowname.isEmpty()) {
						tableList.get(i).addData(rowname, data);
					} else {
						tableList.get(i).addData(data);
					}
				}
			}
		} else {
			tableList.add(new Table(table));
			if (isNewTuple) {
				tableList.get(tableList.size() - 1).nextTuple();
			}
			if (rowname != null || !rowname.isEmpty()) {
				tableList.get(tableList.size() - 1).addData(rowname, data);
			} else {
				tableList.get(tableList.size() - 1).addData(data);
			}
		}
	}

	public boolean isTableExists(String table) {
		if (tableList.isEmpty()) {
			return false;
		} else {
			for (int i = 0; i < tableList.size(); i++) {
				tmp = tableList.get(i);
				if (tmp.getTableName().equals(table)) {
					return true;
				}
			}
		}
		return false;
	}

	public ArrayList<Table> getTables() {
		return this.tableList;
	}

	public Table getTable(String table) {
		if (tableList.isEmpty()) {
			return null;
		} else {
			for (int i = 0; i < tableList.size(); i++) {
				tmp = tableList.get(i);
				if (tmp.getTableName().equals(table)) {
					return tmp;
				}
			}
		}
		return null;
	}

	public void setTables(ArrayList<Table> tableList) {
		this.tableList = tableList;
	}

	// Decodes a JSON file to arraylist of table data
	public ArrayList<Table> decodeFileToArray(String targetFile) {
		return null;
	}

	// Decodes a JSON file to arraylist of table data
	public ArrayList<Table> decodeFileToArray(File targetFile) {
		return null;
	}

	// Decodes a JSON string fragment to arraylist of table data
	public ArrayList<Table> decodeStringToArray(String targetData) {
		return null;
	}

}
